import hashlib

from search_main.utlis import HttpClient


def get_token():
    url = "https://api-media.51cto.com/api/token-get"
    http_client = HttpClient()
    data = http_client.get_client(url)
    return data['data']['data']['data']['token']


def sign(request_path: str,
         payload: dict = None,
         timestamp: int = None,
         token: str = None) -> str:
    payload = payload or {}
    payload.update({
        "timestamp": timestamp,
        "token": token
    })

    # 对参数键进行排序
    sorted_params = ''.join(sorted(payload.keys()))

    # 计算各部分哈希值
    hash_request_path = hashlib.md5(request_path.encode()).hexdigest()
    hash_token = hashlib.md5(token.encode()).hexdigest()
    combined_str = f"{sorted_params}{hash_token}{timestamp}"
    hash_combined = hashlib.md5(combined_str.encode()).hexdigest()

    # 最终签名
    return hashlib.md5((hash_request_path + hash_combined).encode()).hexdigest()


if __name__ == '__main__':
    print(get_token())
    print(sign(
        request_path="/api/test",
        payload={"param1": "value1"},
        timestamp=1689345600,
        token="test_token"
    ))
